from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.http import JsonResponse
from .models import User
from .forms import UserProfileForm, UserRegisterForm

def home(request):
    """首页视图"""
    return render(request, 'index.html')

def register(request):
    """用户注册视图"""
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'账号 {username} 已成功创建！请登录。')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'register.html', {'form': form})

@login_required
def profile(request):
    """用户个人信息视图"""
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人信息更新成功！')
            return redirect('profile')
    else:
        form = UserProfileForm(instance=request.user)
    
    # 获取最近5个订单
    recent_orders = request.user.order_set.all().order_by('-created_at')[:5]
    
    context = {
        'form': form,
        'recent_orders': recent_orders
    }
    return render(request, 'users/profile.html', context)

@login_required
def edit_profile(request):
    """编辑个人信息视图"""
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人信息更新成功！')
            return redirect('profile')
    else:
        form = UserProfileForm(instance=request.user)
    return render(request, 'edit_profile.html', {'form': form})

@login_required
def change_password(request):
    """修改密码视图"""
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, '密码修改成功！')
            return redirect('profile')
        else:
            messages.error(request, '请更正下面的错误。')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'change_password.html', {'form': form})

@login_required
def address_list(request):
    """收货地址列表视图"""
    addresses = request.user.address_set.all()
    return render(request, 'address_list.html', {'addresses': addresses})

@login_required
def add_address(request):
    """添加收货地址视图"""
    if request.method == 'POST':
        address = request.POST.get('address')
        phone = request.POST.get('phone')
        is_default = request.POST.get('is_default', False)
        
        if is_default == 'true':
            # 将其他地址设置为非默认
            request.user.address_set.update(is_default=False)
            
        request.user.address_set.create(
            address=address,
            phone=phone,
            is_default=is_default
        )
        return JsonResponse({'status': 'success'})
    return render(request, 'add_address.html')

@login_required
def delete_address(request, address_id):
    """删除收货地址视图"""
    address = get_object_or_404(request.user.address_set, id=address_id)
    address.delete()
    messages.success(request, '地址已删除')
    return redirect('address_list')

@login_required
def set_default_address(request, address_id):
    """设置默认收货地址视图"""
    if request.method == 'POST':
        address = get_object_or_404(request.user.address_set, id=address_id)
        # 将其他地址设置为非默认
        request.user.address_set.update(is_default=False)
        # 设置新的默认地址
        address.is_default = True
        address.save()
        return JsonResponse({'status': 'success'})
    return JsonResponse({'status': 'error'}, status=400)

@login_required
def my_orders(request):
    """用户订单列表视图"""
    orders = request.user.order_set.all().order_by('-created_at')
    return render(request, 'users/my_orders.html', {'orders': orders})
